package com.lianyu507.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.lianyu507.enums.ErrorTypeEnum;
import com.lianyu507.enums.OrderStatusEnum;
import com.lianyu507.pojo.WechatOrder;
import com.lianyu507.pojo.WechatOrderExample;
import com.lianyu507.service.WechatOrderService;
import com.lianyu507.util.JsonUtils;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.api.WxMpService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 */
@RestController
@RequestMapping("/wechat/pay")
public class PayController extends BaseController {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());


  @Autowired
  private WxMpService wxService;

  @Autowired
  private WxPayService wxPayService;

  @Autowired
  private WechatOrderService wechatOrderService;


  @RequestMapping(value="getSign")
  @ResponseBody
  public Map<String, Object> getSign(@RequestParam String url){
    WxJsapiSignature signature;
    try {
      signature = this.wxService.createJsapiSignature(url);
    }catch(Exception e){
      e.printStackTrace();
      return failedResult(ErrorTypeEnum.SERVER_ERROR,"error");
    }
    return successResult(signature);
  }

  @GetMapping("applyPay")
  public Map<String,Object> applyPay(String openId,String tradeType){

    if(openId==null){
      return this.failedResult(ErrorTypeEnum.VALIDATE_ERROR,"参数错误");
    }

    WechatOrder wechatOrder=new WechatOrder();
    wechatOrder.setOpenId(openId);

    wechatOrder.setOrderNo((new Date()).getTime()+"");
    wechatOrder.setAmount(0.1f);
    wechatOrder.setCreateTime(new Date());
    wechatOrder.setOrderStatus(OrderStatusEnum.NOT_PAY.getValue());

    wechatOrderService.insert(wechatOrder);

    logger.info("[new order]"+ JsonUtils.objectToJson(wechatOrder));


    WxPayUnifiedOrderRequest prepayInfo = new WxPayUnifiedOrderRequest();
    prepayInfo.setOpenid(openId);
    prepayInfo.setOutTradeNo(wechatOrder.getOrderNo());
    Float totalFee=wechatOrder.getAmount()*100;
    prepayInfo.setTotalFee(totalFee.intValue());
    prepayInfo.setBody("土豪打赏");
    prepayInfo.setTradeType(tradeType);
    prepayInfo.setSpbillCreateIp("123.56.134.63");
    prepayInfo.setNotifyURL("http://jjp.zhiyuzhuli.com/ee-wechat/wechat/resultNotify");
    prepayInfo.setProductId(String.valueOf(wechatOrder.getId()));
    logger.info("[prepay info]"+ JsonUtils.objectToJson(prepayInfo));
    try {
      Map<String, String> payInfo = wxPayService.getPayInfo(prepayInfo);
      logger.info("[payInfo]"+ JsonUtils.objectToJson(payInfo));
      return this.successResult(payInfo);
    } catch (WxPayException e) {
      e.printStackTrace();
      this.logger.error(e.getReturnMsg());

      return this.failedResult(ErrorTypeEnum.SERVER_ERROR,e.getReturnMsg());

    }

  }

  @PostMapping("/resultNotify")
  public WxPayOrderNotifyResult parseOrderNotifyResult(@RequestBody String xmlData) throws WxPayException {
    logger.info("[prepay notify]"+ JsonUtils.objectToJson(xmlData));
    WxPayOrderNotifyResult payResult= this.wxPayService.parseOrderNotifyResult(xmlData);
    if(payResult.getReturnCode()!=null && payResult.getReturnCode().equalsIgnoreCase("SUCCESS")){
      String orderNo=payResult.getOutTradeNo();
      if(orderNo!=null){
        WechatOrderExample wechatOrderExample=new WechatOrderExample();
        wechatOrderExample.or().andOrderNoEqualTo(orderNo);
        List<WechatOrder> wechatOrderList=this.wechatOrderService.selectByExample(wechatOrderExample);
        if(wechatOrderList.size()>0){
          WechatOrder wechatOrder=wechatOrderList.get(0);
          wechatOrder.setOrderStatus(OrderStatusEnum.PAY_SUCCESS.getValue());
          wechatOrder.setUpdateTime(new Date());
          this.wechatOrderService.updateByPrimaryKeySelective(wechatOrder);
        }
      }
    }
    return payResult;
  }


}
